package cn.liujinnan.tetris.utils;/*
 *
 * Copyright(c) 2021 by liujinnan.cn All rights Reserved.
 */

import cn.liujinnan.tetris.constant.ExceptionEnum;
import cn.liujinnan.tetris.constant.TetrisCommentConstants;
import cn.liujinnan.tetris.exception.TetrisException;

import java.io.IOException;
import java.util.Objects;
import java.util.Properties;

/**
 * @author LiuJinan
 * @date 2021-08-22 00:07
 */
public class ConfigureUtils {

    private final Properties properties;

    public ConfigureUtils(String propertiesFilePath) {
        properties = new Properties();
        try {
            properties.load(ConfigureUtils.class.getResourceAsStream(propertiesFilePath));
        } catch (IOException e) {
            throw new TetrisException(ExceptionEnum.A_CONFIG_FILE_NOT_EXIST);
        }
    }

    /**
     * 获取字符串配置
     * @param key
     * @return
     */
    public String getStringValue(String key) {
        String val = properties.getProperty(key);
        if (Objects.isNull(val)) {
            throw new TetrisException(ExceptionEnum.A_CONFIG_KEY_NOT_EXIST, "config "+ key + " not exist.");
        }
        return val;
    }

    /**
     * 获取int类型配置
     * @param key
     * @return
     */
    public Integer getIntValue(String key) {
        String val = this.getStringValue(key);
        Integer intVal = null;
        try {
            intVal =  Integer.valueOf(val);
        } catch (Exception e) {
            throw new TetrisException(ExceptionEnum.A_CONFIG_CAST_ERROR, "config "+key+"cast to int error.");
        }
        return intVal;
    }

    /**
     * 获取主配置
     * @return
     */
    public static ConfigureUtils getTetrisProperties() {
        // TODO: 2021-08-24 改造，获取安装目录位置配置，覆盖jar内的配置
        return new ConfigureUtils(TetrisCommentConstants.TETRIS_PROPERTIES_FILE_NAME);
    }
}
